#include <stdio.h>
#include "esp_vfs_fat.h"
#include "sdmmc_cmd.h"
#include "driver/sdmmc_host.h"
#include "esp_log.h"

#define TAG "SD"

#define MOUNT_POINT "/sdcard"
sdmmc_card_t *card;
int sd_init(void)
{
    esp_err_t ret;
    esp_vfs_fat_sdmmc_mount_config_t mount_config = {
        .format_if_mount_failed = true, // 如果挂载不成功是否需要格式化SD卡
        .max_files = 2,
        .allocation_unit_size = 8 * 1024,
    };
    const char mount_point[] = MOUNT_POINT;
    ESP_LOGI(TAG, "Initializing SD card");
    ESP_LOGI(TAG, "Using SDMMC peripheral");

    sdmmc_host_t host = SDMMC_HOST_DEFAULT();                      // SDMMC主机接口配置
    sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); // SDMMC插槽配置
    slot_config.width = 1;                                         // 设置为1线SD模式
    slot_config.clk = CONFIG_SD_CLK_PIN;
    slot_config.cmd = CONFIG_SD_CMD_PIN;
    slot_config.d0 = CONFIG_SD_DATA0_PIN;
    slot_config.flags |= SDMMC_SLOT_FLAG_INTERNAL_PULLUP; // 打开内部上拉电阻

    ESP_LOGI(TAG, "Mounting filesystem");
    ret = esp_vfs_fat_sdmmc_mount(mount_point, &host, &slot_config, &mount_config, &card); // 挂载SD卡
    if (ret != ESP_OK)
    { // 如果没有挂载成功
        if (ret == ESP_FAIL)
        { // 如果挂载失败
            ESP_LOGE(TAG, "Failed to mount filesystem. ");
        }
        else
        { // 如果是其它错误 打印错误名称
            ESP_LOGE(TAG, "Failed to initialize the card (%s). ", esp_err_to_name(ret));
        }
        return ret;
    }
    ESP_LOGI(TAG, "Filesystem mounted"); // 提示挂载成功
    sdmmc_card_print_info(stdout, card); // 终端打印SD卡的一些信息
    return ret;
}
